package com.kk.nb_order.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kk.nb_order.bean.Order;
import com.kk.nb_order.exception.OrderNotFoundException;
import com.kk.nb_order.exception.OrderStatusException;
import com.kk.nb_order.mapper.OrderMapper;
import com.kk.nb_order.remote.*;
import com.kk.nb_order.service.OrderService;
import com.woniuxy.boot.common.bean.Insurance;
import com.woniuxy.boot.common.bean.Policy;
import com.woniuxy.boot.common.bean.PolicyInsurance;
import com.woniuxy.boot.common.dto.OrderPayDTO;
import com.woniuxy.boot.common.dto.PayDTO;
import com.woniuxy.boot.common.util.NOUtil;
import com.woniuxy.boot.common.vo.OrderVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: K
 * @Date: 2024/12/16
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private BankCardService bankCardService;
    @Autowired
    private PolicyService policyService;
    @Autowired
    private InsuranceService insuranceService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private DistributedIDService distributedIDService;
    @Autowired
    private UserService userService;

    /**
     * 生成订单
     *
     * @param orderVO 此vo中包含用户的信息，车辆的信息，保险的信息和保单的id
     */
    @Override
    //@GlobalTransactional
    public void addOrder(OrderVO orderVO) {
        //获取保险列表
        List<Insurance> insurances = orderVO.getInsurances();
        // 用来存放累计的总价格，初始化为零
        BigDecimal totalMoney = BigDecimal.ZERO;
        //循环保险列表
        for (Insurance insurance : insurances) {
            // 累加每个保险的价格
            totalMoney = totalMoney.add(insuranceService.getPrice(insurance.getId()));
        }
        //创建保单对象
        Policy policy = new Policy();
        BeanUtils.copyProperties(orderVO, policy);
        policy.setId(distributedIDService.getDistributeID());
        policy.setNo(NOUtil.getUUIDNO());
        policy.setTotalMoney(totalMoney);
        System.out.println(policy);
        //远程调用，添加保单到数据库
        policyService.add(policy);
        //远程调用，添加保单和保险中间表数据
        List<Insurance> insurances1 = orderVO.getInsurances();
        List<Long> insurancesId = new ArrayList<>();
        for (Insurance insurance : insurances1) {
            insurancesId.add(insurance.getId());
        }
        PolicyInsurance policyInsurance = new PolicyInsurance();
        policyInsurance.setPolicyId(policy.getId());
        policyInsurance.setInsuranceIds(insurancesId);
        policyService.addPolicyInsurance(policyInsurance);
        //创建订单对象
        Order order = new Order();
        BeanUtils.copyProperties(orderVO, order);
        order.setId(distributedIDService.getDistributeID());
        order.setNo(NOUtil.getUUIDNO());
        order.setPolicyId(policy.getId());
        order.setPayStatus("a");
        order.setTotalMoney(totalMoney);
        System.out.println(order);

        //添加订单到数据库
        orderMapper.insert(order);

        //用户此时没支付，生成订单后进入支付倒计时
        PayDTO payDTO = new PayDTO();
        payDTO.setOrderId(order.getId());
        payDTO.setUserId(order.getUserId());
        //发送到mq中
        rabbitTemplate.convertAndSend("orderExchange", "order", payDTO);
    }

    /**
     * 用户支付订单
     *
     * @param orderPayDTO
     */
    @Override
   // @GlobalTransactional
    public void pay(OrderPayDTO orderPayDTO) {
        //调用银行卡模块扣款
        bankCardService.payOrder(orderPayDTO);
        //查询此订单
        Order order = orderMapper.selectById(orderPayDTO.getOrderId());
        if (order == null) {
            throw new OrderNotFoundException("订单不存在");
        }
        if (!order.getPayStatus().equals("a")) {
            throw new OrderStatusException("订单状态异常");
        }

        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //算出保障生效时间，即支付后的第二天
        LocalDateTime plusDays = now.plusDays(1).toLocalDate().atStartOfDay();
        //算出保障失效时间，即365天后
        LocalDateTime localDateTime = plusDays.plusDays(365);
        System.out.println(now);
        System.out.println(plusDays);
        System.out.println(localDateTime);
        //更新订单状态
        orderMapper.update(new LambdaUpdateWrapper<Order>().eq(Order::getNo, order.getNo()).eq(Order::getId, order.getId()).set(Order::getPayStatus, "b").set(Order::getPayTime, now).set(Order::getGuaranteeTime, plusDays));
        //调用policy模块，更新保单数据
        policyService.pay(order.getPolicyId(), plusDays, localDateTime);
        //调用auth模块，更新用户购买的保单数量
        userService.policyNumPlusOne(order.getUserId());
    }
}

